<template>
  <div
      style="
      min-height: 700px;
      background-color: #f5f6f7;
      padding-top: 20px;
      padding-bottom: 40px"
  >
    <el-page-header title="返回首页" @back="goBack" class="back" :icon="ArrowLeft">
      <template #content>
        <i class="title">标题:   </i>
        <el-input class="input"  v-model=article.articleTitle placeholder="文章标题不得小于5个字" size="large"  maxlength="100"/>


      </template>
    </el-page-header>

<!--    //md 编辑器-->
    <v-md-editor
        placeholder="文章内容不得小于100字"
        :disabled-menus="[]"
        @upload-image="handleUploadImage"
        v-model="article.articleContent"
        height="500px"
    >

    </v-md-editor>
    <div style="height: 20px;"></div>
<!--文章属性-->
    <div class="c-foot">
<!--文章封面&简介-->
      <div style="width: 800px;height: 100px;padding-top: 10px">
        <div style="width: 600px;margin-top: 40px;margin-left: 100px">
          <i class="foot-style">文章封面&简介：</i>

          <div class="demo-image__placeholder">
            <!--          图片预览-->
            <div class="block">
              <span class="demonstration">预览图</span>
              <el-image v-if="article.articleCover"
                        :src="article.articleCover"
                        :preview-src-list="srcList"
                        :initial-index="0"
                        fit="cover"
              ></el-image>
              <el-empty v-else description="空图片" />

            </div>
<!--            图片上传-->
            <div class="block">
              <span class="demonstration"
                    id="upload_image"
                    @click="clickfile"
                    style="margin-bottom: 60px"
              >上传图片</span>
              <el-upload
                  class = "avatar-uploader"
                  @click = "clickfile"
                  disabled = true
              >
                <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
              <input
                  id="input_dwad"
                  type="file"
                  style="display: none"
                  accept="image/*"
                  ref="getFile"
                  @change="handle_choseFile"
              />
<!--              文章摘要-->
              <el-input
                  v-model=article.articleIntroduction
                  maxlength="100"
                  placeholder="请输入简介内容，支持一键将正文前 100 字符键入摘要文本框"
                  show-word-limit
                  :disabled="article.status===2"
                  :autosize="{ minRows: 5, maxRows: 6 }"
                  type="textarea"
              />
              <el-button style="float: right" @click="extractText()" round>一键提取</el-button>
            </div>
<!--            文章类型-->
            <div style="margin-bottom: 20px">
              <i class="foot-style" style="margin-right: 20px">文章类型：  </i>
              <el-radio-group v-model="article.type">
                <el-radio :label=1 >原创  </el-radio>
                <el-radio :label=2 >转载  </el-radio>
                <el-radio :label=3 >翻译  </el-radio>
              </el-radio-group>
            </div>
<!--            文章种类-->
            <div style="margin-bottom: 20px">
              <i class="foot-style" style="margin-right: 20px">文章种类：</i>
              <el-select v-model="article.categoryId" class="m-2" placeholder="Select" size="large">
                <el-option
                    v-for="item in options"
                    :key="item.id"
                    :label="item.categoryName"
                    :value="item.id"
                />
              </el-select>
            </div>
<!--            文章的发布方式-->
            <div style="margin-bottom:60px">
              <i class="foot-style" style="margin-right: 20px">发布方式：</i>
              <el-radio-group v-model="article.status">
                <el-radio :label=1 >公开  </el-radio>
                <el-radio :label=2 >私密  </el-radio>
                <el-radio :label=3 >评论可见  </el-radio>
              </el-radio-group>
            </div>
<!--            发布文章-->
            <div>
              <el-button color="darkorange" :dark="isDark" plain style="margin-left: 100px; margin-right: 100px" size="large" round>保存草稿</el-button>
              <el-button type="danger" size="large" @click=submitArticle round >发布文章</el-button>
            </div>

          </div>
            </div>
          </div>


        </div>
      </div>

</template>
<script setup>
import { ArrowLeft } from '@element-plus/icons-vue'
import {reactive, ref} from "vue";
import router from "@/router";
import request from "@/utils/request";
import {ElMessage} from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {onMounted} from "vue-demi";

const text = ref("")
const options = ref([])

const rowsize = reactive({
    minRows: 2,
    maxRows: 6
})
const article = reactive({
  articleTitle: '',
  categoryId: 1,
  type: 1,
  articleCover: '',
  articleContent: '',
  userId: 0,
  status: 1,
  articleIntroduction:''
})
const srcList = ref([
])

//挂载获取作者ID
onMounted(
    async ()=>{
      let result = await request.get("user/getuser")
      let data = result.data
      if(data.code === 200){
        article.userId = data.data.id
        console.log(data.msg)
      }else {
        open(data.msg)
      }
      let result1 = await request.get("article/category")
      let data1 = result1.data
      if(data1.code === 200){
        options.value = data1.data
        console.log(data1.msg)
      }else {
        console.log(data1.msg)
      }
    }
)
/*
返回首页
 */
const goBack = ()=>{
  router.push(name ='/')
}
//上传图片到md编辑器
const handleUploadImage = async (event,insertImage,files)=>{

  for (let i in files) {
    const formData = new FormData()
    formData.append('file',files[i])
    let result = await request.fileUpload("file/upload",formData)
    let data = result.data
    if(data.code === 200){
      // text.value = text.value + '!['+data.data.desc+']' + '(' + data.data.url + ')'
      insertImage({url:data.data.url,desc:data.data.desc})
      open(data.msg)
      console.log(data.msg);
    }else{
      open(data.msg)
      console.log(data.msg)
    }
    console.log(formData)
  }

}
//提示信息
const open = (msg) => {
  ElMessage({
    message: msg,
    type: 'warning',
  })
}
const open1 = (msg) => {
  ElMessage({
    message: msg,
    type: 'success',
  })
}

//上传文章缩略图
const emit = defineEmits(['update:fileUrl'])
defineProps({
  fileUrl: {
    type: String,
    default: ""
  },
})


const getFile = ref(null)
function handle_doUpload() {
  getFile.value.click()
}
async function handle_choseFile(e) {
  let file = getFile.value.files[0]
  if (file.size > 10 * 1024 * 1024) {
    // 文件大小超限了
    ElMessage.closeAll()
    ElMessage({
      type: 'error',
      showClose: true,
      message: '请上传小于10M的图片'
    })
    getFile.value.value = '' // 清空内容
    return
  }
  let forms = new FormData()
  forms.append('file', file)

  let result = await request.fileUpload("file/upload",forms)
  let data = result.data
  if(data.code === 200){
    article.articleCover = data.data.url
    srcList.value.push(data.data.url)
    open(data.msg)
    console.log(data.msg);
  }else{
    open(data.msg)
    console.log(data.msg)
  }
}

const clickfile = ()=>{
  const input = document.querySelector('#input_dwad')
  input.click()
}
//发布文章
const submitArticle = async ()=>{
  if(article.userId === 0){
    open("用户ID为空")
    return
  }else if(article.articleTitle === ''){
    open("标题不能为空")
    return
  }else if(article.articleTitle.length <= 5){
    console.log('标题共'+ article.articleTitle.length +'个字')
    open("标题不得小于5个字")
    return
  }else if(article.articleContent.length <= 100){
    open("文章内容不得小于100个字")
    return
  }else if(article.articleCover === ''){
    open("文章缩略图不能省略")
    return
  }else if(article.articleIntroduction === ''|| article.status === 2){
    open('非私密文章，简介不能为空')
    return
  }


  let result = await request.post("createarticle",article)
  let data = result.data
  if(data.code === 200){
    open1(data.msg)
    router.push(name='/')
  }else {
    open(data.msg)
  }
}
const extractText = ()=>{
  if(article.status === 2){
    open('私密文章不需键入简介')
  }else if(article.articleContent.length<=100){
    article.articleIntroduction = article.articleContent
  } else {
    article.articleIntroduction = article.articleContent.substring(0,100)
  }

}
</script>
<style>
.back{
  margin-top: -16px;
  margin-bottom: 20px;
}
.title{
  margin-top: 30px;
  font-size: 30px;
}
.input{
  height: 50px;
  font-weight: 900;
  font-size: 40px;
  width:450px
}
.c-foot{
  box-shadow: 5px 5px 30px #b0b0b0;
  border-radius: 30px;
  /*text-align: center;*/
  height: 800px;
  width: 800px;
  background-color: #ffffff;
  margin: auto;
}
.foot-style{
  font-weight: bold;
  font-size: 20px;
}
.demo-image__placeholder .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  display: inline-block;
  width: 49%;
  box-sizing: border-box;
  vertical-align: top;
}
.demo-image__placeholder .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

</style>